<template>
  <view class="ad-history-container">
    <!-- 顶部栏 -->
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="header-title">广告历史记录</text>
      <view class="clear-btn" @tap="clearAllHistory">
        <text class="clear-text">清除</text>
      </view>
    </view>
    
    <!-- 筛选器 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          class="filter-tab"
          :class="{ 'active': activeFilter === 'all' }"
          @tap="setFilter('all')"
        >
          <text class="tab-text">全部</text>
        </view>
        <view 
          class="filter-tab"
          :class="{ 'active': activeFilter === 'video' }"
          @tap="setFilter('video')"
        >
          <text class="tab-text">视频</text>
        </view>
        <view 
          class="filter-tab"
          :class="{ 'active': activeFilter === 'banner' }"
          @tap="setFilter('banner')"
        >
          <text class="tab-text">横幅</text>
        </view>
        <view 
          class="filter-tab"
          :class="{ 'active': activeFilter === 'reward' }"
          @tap="setFilter('reward')"
        >
          <text class="tab-text">激励</text>
        </view>
      </view>
      
      <view class="date-filter" @tap="showDatePicker">
        <text class="date-text">{{ dateRangeText }}</text>
        <text class="arrow-icon">↓</text>
      </view>
    </view>
    
    <!-- 历史记录列表 -->
    <view class="history-list" v-if="filteredAds.length > 0">
      <view 
        class="ad-item"
        v-for="ad in filteredAds"
        :key="ad.id"
        @tap="viewAdDetails(ad.id)"
      >
        <!-- 广告类型标记 -->
        <view class="ad-type-badge" :class="ad.type">
          <text class="badge-text">{{ getAdTypeText(ad.type) }}</text>
        </view>
        
        <!-- 广告内容 -->
        <view class="ad-content">
          <text class="ad-title">{{ ad.title }}</text>
          <text class="ad-description">{{ ad.description }}</text>
          <text class="ad-time">{{ formatTime(ad.timestamp) }}</text>
        </view>
        
        <!-- 广告图片 -->
        <view class="ad-image" v-if="ad.image">
          <image :src="ad.image" mode="aspectFill"></image>
        </view>
        
        <!-- 操作按钮 -->
        <view class="ad-actions">
          <view class="action-btn" @tap.stop="blockAd(ad.id)">
            <text class="action-icon">🚫</text>
            <text class="action-text">不感兴趣</text>
          </view>
          <view class="action-btn" @tap.stop="viewAdDetails(ad.id)">
            <text class="action-icon">👁️</text>
            <text class="action-text">详情</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <text class="empty-icon">📝</text>
      <text class="empty-text">暂无广告历史记录</text>
      <text class="empty-desc">当您查看广告后，这里会显示相关记录</text>
    </view>
    
    <!-- 底部统计 -->
    <view class="stats-section" v-if="filteredAds.length > 0">
      <text class="stats-text">共 {{ filteredAds.length }} 条记录</text>
      <view class="frequency-info">
        <text class="frequency-text">平均每天查看 {{ averageDailyAds }} 条广告</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 筛选条件
      activeFilter: 'all', // 'all', 'video', 'banner', 'reward'
      dateRange: { start: null, end: null },
      dateRangeText: '近7天',
      
      // 模拟广告历史数据
      adHistory: [
        {
          id: 'ad1',
          type: 'video',
          title: '全新智能手机体验',
          description: '搭载最新处理器，超长续航，限时优惠200元',
          image: 'https://img.yzcdn.cn/vant/cat.jpeg',
          timestamp: Date.now() - 86400000 * 1 // 1天前
        },
        {
          id: 'ad2',
          type: 'banner',
          title: '双11购物节',
          description: '全场商品低至5折，限时抢购',
          image: 'https://img.yzcdn.cn/vant/apple-1.jpg',
          timestamp: Date.now() - 86400000 * 2 // 2天前
        },
        {
          id: 'ad3',
          type: 'reward',
          title: '观看视频得积分',
          description: '观看完整视频可获得100积分，积分可兑换好礼',
          image: 'https://img.yzcdn.cn/vant/apple-2.jpg',
          timestamp: Date.now() - 86400000 * 3 // 3天前
        },
        {
          id: 'ad4',
          type: 'video',
          title: '精品旅游线路推荐',
          description: '限时特惠，满1000减200，说走就走的旅行',
          image: 'https://img.yzcdn.cn/vant/apple-3.jpg',
          timestamp: Date.now() - 86400000 * 4 // 4天前
        },
        {
          id: 'ad5',
          type: 'banner',
          title: '健康生活新方式',
          description: '科学健身，均衡饮食，从现在开始',
          image: 'https://img.yzcdn.cn/vant/apple-4.jpg',
          timestamp: Date.now() - 86400000 * 5 // 5天前
        }
      ],
      
      // 过滤后的广告列表
      filteredAds: []
    };
  },
  onLoad() {
    // 加载广告历史数据
    this.loadAdHistory();
    // 初始化过滤
    this.filterAds();
  },
  computed: {
    // 计算平均每天查看的广告数量
    averageDailyAds() {
      const days = this.getDaysInRange();
      if (days === 0) return 0;
      return (this.filteredAds.length / days).toFixed(1);
    }
  },
  methods: {
    // 加载广告历史数据
    loadAdHistory() {
      // 模拟从本地存储加载广告历史
      const savedHistory = uni.getStorageSync('adHistory');
      if (savedHistory !== '') {
        this.adHistory = JSON.parse(savedHistory);
      } else {
        // 如果没有保存的数据，使用默认数据
        this.saveAdHistory();
      }
    },
    
    // 保存广告历史数据
    saveAdHistory() {
      uni.setStorageSync('adHistory', JSON.stringify(this.adHistory));
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 设置筛选条件
    setFilter(filter) {
      this.activeFilter = filter;
      this.filterAds();
    },
    
    // 显示日期选择器
    showDatePicker() {
      // 模拟日期选择器
      const options = [
        { text: '近7天', value: '7' },
        { text: '近30天', value: '30' },
        { text: '近90天', value: '90' },
        { text: '今年', value: 'year' },
        { text: '全部', value: 'all' }
      ];
      
      uni.showActionSheet({
        itemList: options.map(option => option.text),
        success: (res) => {
          const selectedOption = options[res.tapIndex];
          this.dateRangeText = selectedOption.text;
          this.filterAds();
        }
      });
    },
    
    // 过滤广告
    filterAds() {
      // 根据类型过滤
      let filtered = this.adHistory;
      
      if (this.activeFilter !== 'all') {
        filtered = filtered.filter(ad => ad.type === this.activeFilter);
      }
      
      // 根据日期过滤
      const now = Date.now();
      let timeRange = 0;
      
      switch (this.dateRangeText) {
        case '近7天':
          timeRange = 7 * 86400000;
          break;
        case '近30天':
          timeRange = 30 * 86400000;
          break;
        case '近90天':
          timeRange = 90 * 86400000;
          break;
        case '今年':
          const startOfYear = new Date(new Date().getFullYear(), 0, 1).getTime();
          filtered = filtered.filter(ad => ad.timestamp >= startOfYear);
          break;
        case '全部':
        default:
          // 不过滤日期
          break;
      }
      
      if (timeRange > 0) {
        filtered = filtered.filter(ad => now - ad.timestamp <= timeRange);
      }
      
      // 按时间倒序排列
      filtered.sort((a, b) => b.timestamp - a.timestamp);
      
      this.filteredAds = filtered;
    },
    
    // 获取广告类型文本
    getAdTypeText(type) {
      const typeMap = {
        'video': '视频',
        'banner': '横幅',
        'reward': '激励',
        'interstitial': '插屏'
      };
      return typeMap[type] || '未知';
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const now = Date.now();
      const diff = now - timestamp;
      
      if (diff < 86400000) {
        // 一天内
        const hours = Math.floor(diff / 3600000);
        if (hours < 1) {
          const minutes = Math.floor(diff / 60000);
          return minutes < 1 ? '刚刚' : `${minutes}分钟前`;
        }
        return `${hours}小时前`;
      } else if (diff < 7 * 86400000) {
        // 一周内
        const days = Math.floor(diff / 86400000);
        return `${days}天前`;
      } else {
        // 超过一周
        const date = new Date(timestamp);
        return `${date.getMonth() + 1}月${date.getDate()}日`;
      }
    },
    
    // 获取日期范围内的天数
    getDaysInRange() {
      switch (this.dateRangeText) {
        case '近7天': return 7;
        case '近30天': return 30;
        case '近90天': return 90;
        case '今年': 
          const now = new Date();
          const startOfYear = new Date(now.getFullYear(), 0, 1);
          return Math.floor((now - startOfYear) / (1000 * 60 * 60 * 24)) + 1;
        default: return 30; // 默认30天
      }
    },
    
    // 查看广告详情
    viewAdDetails(adId) {
      const ad = this.adHistory.find(a => a.id === adId);
      if (ad) {
        uni.showModal({
          title: ad.title,
          content: `广告类型：${this.getAdTypeText(ad.type)}\n\n${ad.description}\n\n查看时间：${this.formatTime(ad.timestamp)}`,
          showCancel: false
        });
      }
    },
    
    // 屏蔽广告
    blockAd(adId) {
      uni.showModal({
        title: '不感兴趣',
        content: '确定要将此广告标记为不感兴趣吗？未来将减少类似广告的展示。',
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 从列表中移除广告
            const index = this.adHistory.findIndex(ad => ad.id === adId);
            if (index > -1) {
              this.adHistory.splice(index, 1);
              this.saveAdHistory();
              this.filterAds();
            }
            
            uni.showToast({
              title: '已标记为不感兴趣',
              icon: 'success'
            });
          }
        }
      });
    },
    
    // 清除所有历史记录
    clearAllHistory() {
      uni.showModal({
        title: '清除历史记录',
        content: '确定要清除所有广告历史记录吗？此操作无法撤销。',
        confirmText: '确定',
        cancelText: '取消',
        confirmColor: '#ff4d4f',
        success: (res) => {
          if (res.confirm) {
            // 清空广告历史
            this.adHistory = [];
            this.saveAdHistory();
            this.filterAds();
            
            uni.showToast({
              title: '历史记录已清除',
              icon: 'success'
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.ad-history-container {
  height: 100vh;
  background-color: #f8f9fc;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 顶部栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.back-btn {
  padding: 10rpx;
}

.back-icon {
  font-size: 32rpx;
  color: #333;
}

.header-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.clear-btn {
  padding: 10rpx 20rpx;
}

.clear-text {
  font-size: 32rpx;
  color: #ff4d4f;
}

/* 筛选器 */
.filter-section {
  background-color: #fff;
  padding: 0 40rpx 20rpx 40rpx;
  margin-bottom: 20rpx;
}

.filter-tabs {
  display: flex;
  margin-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.filter-tab {
  padding: 20rpx 30rpx;
  margin-right: 20rpx;
}

.filter-tab.active {
  border-bottom: 3rpx solid #07c160;
}

.tab-text {
  font-size: 28rpx;
  color: #666;
}

.filter-tab.active .tab-text {
  color: #07c160;
  font-weight: 600;
}

.date-filter {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.date-text {
  font-size: 28rpx;
  color: #333;
}

.arrow-icon {
  font-size: 24rpx;
  color: #666;
  margin-left: 10rpx;
}

/* 历史记录列表 */
.history-list {
  background-color: #fff;
}

.ad-item {
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #eee;
  position: relative;
}

.ad-item:last-child {
  border-bottom: none;
}

/* 广告类型标记 */
.ad-type-badge {
  position: absolute;
  top: 30rpx;
  right: 40rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.ad-type-badge.video {
  background-color: #e6f7ff;
  color: #1890ff;
}

.ad-type-badge.banner {
  background-color: #f6ffed;
  color: #52c41a;
}

.ad-type-badge.reward {
  background-color: #fff2e8;
  color: #fa8c16;
}

.ad-type-badge.interstitial {
  background-color: #f9f0ff;
  color: #722ed1;
}

.badge-text {
  font-size: 24rpx;
}

/* 广告内容 */
.ad-content {
  margin-right: 120rpx; /* 为类型标记留出空间 */
  margin-bottom: 20rpx;
}

.ad-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.ad-description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 10rpx;
  display: block;
}

.ad-time {
  font-size: 24rpx;
  color: #999;
  display: block;
}

/* 广告图片 */
.ad-image {
  width: 100%;
  height: 300rpx;
  margin-bottom: 20rpx;
}

.ad-image image {
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
}

/* 操作按钮 */
.ad-actions {
  display: flex;
  justify-content: flex-start;
  gap: 40rpx;
}

.action-btn {
  display: flex;
  align-items: center;
}

.action-icon {
  font-size: 28rpx;
  margin-right: 8rpx;
}

.action-text {
  font-size: 26rpx;
  color: #666;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: #999;
  text-align: center;
}

/* 底部统计 */
.stats-section {
  padding: 30rpx 40rpx;
  background-color: #fff;
  margin-top: 20rpx;
}

.stats-text {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.frequency-info {
  padding: 15rpx;
  background-color: #f0f9f4;
  border-radius: 10rpx;
}

.frequency-text {
  font-size: 26rpx;
  color: #07c160;
  display: block;
}
</style>